<template>
    <Header />
    <v-md-editor
        :height="`${height}px`"
        v-model="content"
        @save="save"
        :disabled-menus="[]"
        @upload-image="pasteImage"
    ></v-md-editor>
    <el-dialog v-model="dialogVisible" title="保存" width="30%">
        <el-input v-model="title" placeholder="请输入标题"></el-input>
        <br />
        <br />
        <el-select v-model="type" placeholder="文集">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
        </el-select>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue';

import request from '@/api';
import router from '@/router';
import { useRouter } from 'vue-router';
import store from '@/store';
import { Upload } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import Header from '@/components/Header.vue';
const content = ref('');
const title = ref('');
const type = ref(0);
const describe = ref('');
const dialogVisible = ref(false);
// 记录原始文章数据，用于比较是否有修改
const oldData = ref('');
const height = ref(document.body.clientHeight - 60);
const options = ref([
    {
        id: 0,
        name: '未分类',
    },
]);

// 类型列表请求
request.get('/GetArticleType').then(res => {
    options.value = [...options.value, ...res.data];
});

if (router.currentRoute.value.params.id[0]) {
    const id = router.currentRoute.value.params.id[0];
    request({
        url: '/GetArticleById/' + id,
        method: 'get',
    }).then(res => {
        content.value = res.data.content;
        title.value = res.data.title;
        type.value = res.data.typeId;
        oldData.value = res.data.content;
    });
}

const save = (text: string, html: string) => {
    if (text.trim() === '') {
        ElMessage.error('内容不能为空');
        return;
    }

    // 过滤html中的标签和pre标签中的内容
    const reg = /<\/?[^>]+>/g;
    const regPre = /<pre[^>]*>([\s\S]*?)<\/pre>/g;
    const htmlStr = html.replace(regPre, '').replace(reg, '');
    let str = JSON.stringify(htmlStr)
        .replace(/\s+/g, ' ')
        .replaceAll('\\n', '')
        .replaceAll('\\t', '')
        .replace(/^"|"$/g, '');
    describe.value = str.length > 200 ? str.substring(0, 200) + '...' : str;
    // 取出html中的第一个h1标签
    const regH1 = /<h1[^>]*>([\s\S]*?)<\/h1>/g;
    const h1 = regH1.exec(html);
    if (!router.currentRoute.value.params.id[0] && h1) {
        title.value = h1[1];
    }

    dialogVisible.value = true;
};
const submit = () => {
    if (title.value.trim() === '') {
        ElMessage.error('标题不能为空');
        return;
    }
    // 标题不能超过100个字符
    if (title.value.length > 100) {
        ElMessage.error('标题不能超过100个字符');
        return;
    }

    request({
        url: '/UploadArticle',
        method: 'post',
        data: {
            id: router.currentRoute.value.params.id[0] || 0,
            title: title.value,
            content: content.value,
            describe: describe.value,
            typeId: type.value,
            userId: store.state.userinfo.userId,
        },
    }).then(res => {
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        router.push('/');
    });
};

const pasteImage = (event: any, insertImage: any, files: any) => {
    // 读取剪贴板图片
    request({
        url: '/upload',
        method: 'post',
        headers: { 'Content-Type': 'multipart/form-data' },
        timeout: 50000,
        data: { type: 'img', file: files[0] },
    }).then(res => {
        insertImage({
            url: window.baseurl + res.data.path,
            desc: new Date().getTime(),
        });
    });
};

window.onresize = () => {
    height.value = document.body.clientHeight - 60;
};
</script>
